import wepy from 'wepy'
const request = async (url = '', params = {}) => {
  try {
    let res
    let host = wepy.$appConfig.baseUrl
    let {
      method = 'POST',
      data = {
        base:{},
        buss:{}
      },
      header = { "Content-Type": "application/json" },
      isNeedToken = true
    } = params;
    // 读取token
    try {
      var value = wepy.getStorageSync('TOKEN');
      if (value) {
        data.base.usertoken = value;
      }
    } catch (e) {
      console.log("token报错：" + e)
    }
    url = host + url
    res = isNeedToken ? await wepy.request({ url, method, data, header }) : await wepy.request({ url, method, data, header });
    let { statusCode } = res;
    if (typeof statusCode === 'undefined' || statusCode !== 200) {
      wepy.showToast({
        title: '服务器异常，请重试',
        icon: 'none'
      })
    } else {
      let { data } = res;
      if(data.base.successCode === '1'){
        //失败
        wepy.showToast({
          title: data.base.successMsg,
          icon: 'none'
        })
        return false;
      } else if(data.base.successCode === '0') {
        //成功
        return res.data;
      }else if(data.base.successCode === '9'){
        //token过期
          wepy.showToast({
              title: '请登录！',
              icon: 'none'
          });
          setTimeout(()=>{
              wepy.redirectTo({
                  url: '/pages/auth/login'
              });
          },1500);
      }
    }
  } catch (error) {
    console.log(`error! errUrl: ${url}, errParams:`, params)
    console.log("报错:" + JSON.stringify(error));
  }
}

export default request
